﻿
CREATE PROCEDURE [dbo].[proc_Order_Change_CCreate]
	(
		@OId uniqueidentifier
		,@CusId	uniqueidentifier
		,@CusName nvarchar(200)
		,@shqr varchar(20)
		,@shqrxm nvarchar(50)
		,@shqrq datetime
		,@oldje	decimal(18, 2)
		,@newje	decimal(18, 2)
		,@bgnr text
		,@CompanyId	int
		,@ChangeType int
	)
AS
Begin
	Declare @flag int,@rq datetime,@r int,@stateId int
	Set @r=0
	--不能变更
	Select @stateId=StateId from [Order] where OId=@OId
	If @stateId<=2 
	begin
		Select @stateId As ReturnValue
		return
	end

	Select Top 1 @flag=flag,@rq=shqrq From [Order_Change] Where OId=@OId And flag<>-1 Order By shqrq Desc
	If @flag Is Not Null
	Begin
		If @flag=0 Or @flag=1
		Begin
			Select @flag As ReturnValue	--该成单已提交变更
			Return
		End

		If Convert(varchar(10),@rq,23)=Convert(varchar(10),GetDate(),23)
		Begin
			Select -1 As ReturnValue		--今天已变更过
			Return
		End
--		If Convert(varchar(10),@rq,23)=Convert(varchar(10),GetDate(),23)
--		Begin
--			Select @flag=IsNull(Count(0),0) From [Order_Change] Where OId=@OId And Convert(varchar(10),@rq,23)=Convert(varchar(10),GetDate(),23)
--			If @flag > 3	--每天3次
--			Begin
--				Select -1 As ReturnValue		--今天已变更过
--				Return
--			End
--		End

		Set @r=1
	End
	Else
		Set @r=1

	If @r=1
	Begin
		Insert Into [Order_Change]
		(
			OId
			,CusId
			,CusName
			,shqr
			,shqrxm
			,shqrq
			,oldje
			,newje
			,bgnr
			,CompanyId
			,ChangeType
		)
		Values
		(
			@OId
			,@CusId
			,@CusName
			,@shqr
			,@shqrxm
			,@shqrq
			,@oldje
			,@newje
			,@bgnr
			,@CompanyId
			,@ChangeType
		)

		Select 2 As ReturnValue
	End
End